package com.fishingwithme.infrastructure;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import java.io.IOException;

import java.util.HashMap;
import java.util.Map;

public class WeChatLoginFilter extends AbstractAuthenticationProcessingFilter {

    public WeChatLoginFilter() {
        super(new AntPathRequestMatcher("/user/loginwx", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException, IOException {
        // 使用Fastjson2解析JSON为Map
        ObjectMapper objectMapper = new ObjectMapper();
        Map requestParams = objectMapper.readValue(request.getInputStream(), Map.class);
        if (requestParams == null) {
            requestParams = new HashMap<>();
        }

        // 获取并处理参数
        String code = String.valueOf(requestParams.getOrDefault("wxCode", ""));
        String username = String.valueOf(requestParams.getOrDefault("username", ""));
        String nickName = String.valueOf(requestParams.getOrDefault("nickName", ""));
        String avatarUrl = String.valueOf(requestParams.getOrDefault("avatarUrl", ""));

        code = StringUtils.trim(code);

        // 创建认证令牌并进行认证
        WeChatAuthenticationToken authRequest = new WeChatAuthenticationToken(code, username, nickName, avatarUrl);
        setDetails(request, authRequest);

        return getAuthenticationManager().authenticate(authRequest);
    }

    private void setDetails(HttpServletRequest request, WeChatAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }
}
